<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
    .avatar {
      width: 100px;
      height: 100px;
      display: flex;
      /* border-radius: 50%; */
      /* background-color: hotpink; */
      justify-content: center;
      align-items: center;
      overflow: hidden;
    }
  </style>
</head>

<body>
  <div class="avatar">
    <img width="100px" src="" alt="">
  </div>
  <input type="file" οnchange="sendFile()" id="up" name="up" />
  <p></p>
  <input type="button" name="" value="提交" id="" onclick="sendFile()">
  <script>
    let $img = document.getElementsByTagName("img")[0];
    let $input = document.getElementsByName("up")[0];
    $input.addEventListener("change", changeHandler);

    function changeHandler() {
      //显示选中的图片
      let f = $input.files[0];
      let src = window.URL.createObjectURL(f);
      $img.src = src;
    }

    function sendFile() {
      var fd = new FormData();
      var pic = document.getElementById("up").files[0];
      var type = pic.type; //文件类型

      if (type != "image/jpeg" && type != "image/png") {
        alert("请上传正确格式图片");
        return false;
      }

      var size = parseInt(pic.size) / 1024 / 1024; //文件大小（换算成 M）

      if (size > 5) {
        alert('文件过大');
        return false;
      }

      fd.append(pic.name, pic);
      var xhr = new XMLHttpRequest();
      xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
          let msg = xhr.responseText;
          // console.log('msg: ', msg);
          alert(msg);
        }
      }
      let url = "http://127.0.0.1:8080/v1/users/upimg" + location.search;
      xhr.open("POST", url, true);
      xhr.send(fd);
    }
  </script>
</body>

</html>